<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/11/9  19:27
 */
namespace app\api\logic;
use app\api\BaseModel;
use think\Cache;

class Goods extends  BaseModel{


    /**
     * 分类列表
     */
    public function category(){
        $data = db("goods_category")->field('id,name,image,p_id')
            ->where(['status' => 1])
            ->order("sort desc")
            ->select();
        $list = array();
        if(!empty($data)){
            foreach ($data as &$d){
                $d['image'] = IMG_PATH.str_replace('\\',"/",$d['image']);
            }
            $pids = array_column($data,'p_id');
            $data_count = array_count_values($pids);
            $list = array_slice($data,0,$data_count[0]);
            foreach ($list as &$l){
                if(array_key_exists($l['id'],$data_count)){
                    $l['children'] = array_slice($data,array_search($l['id'],$pids),$data_count[$l['id']]);
                }
            }
        }
        return $list;
    }

    /**
     * 商品列表
     */
    public function index()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $sort=isset($this->requestData['sort'])?$this->requestData['sort']:'0';
        switch($sort){
            case 0:$order='id desc';break;
            case 1:$order='sales_num desc';break;
            case 2:$order='price asc';break;
            case 3:$order='price desc';break;
        }
        $goods = db('goods');
        $goods_option_value=db('goods_option_value');
        if (isset($this->requestData['cid'])) {//分类
            $where['cid'] = $this->requestData['cid'];
        }
        if (array_key_exists('bid',$this->requestData)){
            $where['brand_id'] = $this->requestData['bid'];
        }
        $where['status']=1;
        $list=$goods->alias("g")
            ->field("g.id,g.name,g.image,g.sales_num,g.des,min(p.price) as price")
            ->join("goods_option_value p","p.goodsid=g.id")
            ->where($where)
            ->group("g.id")
            ->order($order)->page($p,$size)->select();
        foreach($list as &$v){
            $v['image']=IMG_PATH.str_replace('\\',"/",$v['image']);
        }
        $data['data']=$list;
        $data['count']=$goods->where($where)->count();
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }

    /**
     * 搜索商品
     */
    public function search_goods(){
        if(!isset($this->requestData['keyword']))return array('message'=>'缺少搜索商品名称参数');
        $goods_name = $this->requestData['keyword'];

        $where['g.name'] = array('like',"%$goods_name%");
        $where['g.status'] = '1';
        $list=db('goods')->alias("g")
            ->field("g.id,g.name,g.image,g.des,min(p.price) as price,min(p.oldprice) as oldprice")
            ->join("goods_option_value p","p.goodsid=g.id")
            ->where($where)
            ->group("g.id")
            ->select();

        //热搜
        $hot_search_goods = Cache::get("hot_search_goods");
        $hot_search_goods = json_decode($hot_search_goods);
        $hot_search_goods[] = $goods_name;

        Cache::set("hot_search_goods", json_encode($hot_search_goods), 864000);
        //热搜

        return $list;
    }


    /**
     * 商品详情
     */
    public function detail(){
        $where['id'] = intval($this->requestData['id']);
        $where['status']=1;
        $list= db('goods')->field('id,name,image,images,des,content')
            ->where($where)
            ->find();
        if(!$list) return array('message'=>'商品不存在');

        $list['content'] = str_replace('/ueditor/php/upload/imag',config('host_url').'/ueditor/php/upload/imag',htmlspecialchars_decode($list['content']));

        if($list['image']) {
            $list['image']=IMG_PATH .str_replace('\\',"/",$list['image']);
        }
        if(!empty($list['images'])) {
            $list['images'] = unserialize($list['images']);
            foreach ($list['images'] as $k => $v) {
                $list['images'][$k] = IMG_PATH .str_replace('\\',"/",$v);
            }
        }else{
            $list['images'] = array();
        }


        //查询商品价格最高价与最低价
        $goods_option_value_result = db('goods_option_value')->where(array('goodsid'=>$where['id']))->group('goodsid')->field('max(price) as price_max,min(price) as price_min')->find();

        $list['price_max'] = $goods_option_value_result['price_max'];
        $list['price_min'] = $goods_option_value_result['price_min'];



        return $list;
    }

    /*
      * 规格列表
      */
    public function spec()
    {
        $id = intval($this->requestData['id']);
        if (!$id) return array('message' => '参数有误');
        $goods = db('goods')->field('id,image,name')
            ->where(['id' => $id])
            ->find();
        if(!$goods) return array('message' => '找不到商品');
        $goods['image'] = IMG_PATH .str_replace('\\',"/", $goods['image']);
        $data['goods'] = $goods;
        $where['goodsid'] = $id;
        $spec = db("goods_option_category")->field("id,title")
            ->where($where)
            ->order("id asc")
            ->select();
        foreach ($spec as &$v) {
            $v['list'] = db("goods_option")->field("title,id")
                ->where("option_category=".$v['id'])
                ->select();
        }
        $data['specs'] = $spec;
        //组合结果
        $data['groups'] = db("goods_option_value")->field('id,price,stock,spec_name,specs')
            ->where($where)
            ->select();

        return $data;
    }

}